package tech.senri.iot.socket.service.util

import io.netty.buffer.ByteBuf
import kotlin.experimental.and

private val HEX_CHARS = "0123456789ABCDEF".toCharArray()

fun ByteArray.toHex(): String
{
    val result = StringBuffer()

    forEach {
        val octet = it.toInt()
        val firstIndex = (octet and 0xF0).ushr(4)
        val secondIndex = octet and 0x0F
        result.append(HEX_CHARS[firstIndex])
        result.append(HEX_CHARS[secondIndex])
    }

    return result.toString()
}

fun Byte.toBits(): ByteArray
{
    val array = ByteArray(8)
    var b = this
    for (i in 7 downTo 0)
    {
        array[i] = (b and 1)
        b = (b.toInt() shr 1).toByte()
    }
    return array
}

fun ByteBuf.getArray(): ByteArray
{
    val result = ByteArray(readableBytes())
    readBytes(result)
    release()
    return result
}
